﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using ABC.Google;

namespace AbcFastFix2010.Maps
{
    public partial class Maps : System.Web.UI.Page
    {
        private System.DateTime startDate;
        private System.DateTime endDate;
        private Boolean showTrips;
        private Boolean showWOOnsitePartsReceived;
        private Boolean showUnitRequiringMoreInfo;
        private Boolean showPartsIn7OrLessDays;
        private List<ABC.Google.PartsIn7orLessDays> ListOfParts7OrLessDays;
        private ABC.Google.MapMarkerCollection<ABC.Google.UnitsRequiringMoreInfo> ListOfUnitsNeedingMoreInfo;
        private ABC.Google.MapMarkerCollection<ABC.Google.WOONsitePartsReceived> ListOfOnSitePartsReceived;
        private ABC.Google.MapMarkerCollection<ABC.Google.currentTrips> currTrips;
        private ABC.Google.MapMarkerCollection<ABC.Google.DealerPickUpRequest> currDealerTrips;
        private Boolean showDealerTrips;
        private List<string> listOfUnfindableAddresses = new List<string>();

        protected void Page_Load(object sender, EventArgs e)
        {   
            if (Page.IsPostBack)
            {
                //DropDownTechs.SelectedValue = Session["SelectTech"].ToString();
            }

            if (Page.IsPostBack == false)
            {
                DayPilotCalendar1.StartDate = startDate;
                DayPilotCalendar1.Days = Convert.ToInt16((endDate - startDate).TotalDays) + 1;
                DayPilotCalendar1.DataStartField = "start";
                DayPilotCalendar1.DataEndField = "end";
                DayPilotCalendar1.DataTextField = "name";
                DayPilotCalendar1.DataValueField = "id";


                DropDownTechs.DataSource = ABC.Tech.Tech.getListOfTechInitials();
                DropDownTechs.DataBind();
                departmentsDropDown.DataSource = ABC.General.Departments.getDepartmentList();
                departmentsDropDown.DataBind();
                categoriesDropDown.DataSource = ABC.General.Categories.getListOfCategories();
                categoriesDropDown.DataBind();

                //Do not need these default values anymore.. doing validations on client side. 
                //txtStartDate.Text = "Start Date";
                //txtEndDate.Text = "End Date";
            }
        }
        /// <summary>
        /// Creates the Java Script Code
        /// </summary>
        private void BuildScript()
        {

            // construct the final script
            StringBuilder sb = new StringBuilder();

            sb.Append(@"        
            <script type='text/javascript'>
            window.onload = function() {
             // Creating a MapOtions object with the required properties
                var options = {
                    zoom: 10,
                      center: new google.maps.LatLng(42.899,-77.4806270),
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                             };
               // Creating the map
               var map = new google.maps.Map(document.getElementById('map_canvas'), options);
 
               //Creating a LatLngBounds object
               var bounds = new google.maps.LatLngBounds();
            
               //display ABC's Marker
               var myLatLng = new google.maps.LatLng(43.1158400,-77.4806270);
               var abcmarker = new google.maps.Marker({
                                        position: myLatLng,
                                        map: map,
                                        icon: '../icons/ABCMarker.png',
                                        title: 'ABC Electronics', 
                                        animation: google.maps.Animation.DROP    
                                    });
                
                ");
            if (showWOOnsitePartsReceived == true)
            {
                sb.Append("   displayMarkers(map, woOnSitePartsReceived,'../icons/yellow01.png');");
            }
            if (showUnitRequiringMoreInfo == true)
            {
                sb.Append("   displayMarkers(map, unitsRequiringMoreInfo,'../icons/green01.png');");
            }
            if (showPartsIn7OrLessDays == true)
            {
                sb.Append("   displayMarkers(map, partsIn7OrLessDays,'../icons/purple01.png');");
            }
            if (showTrips)
            {
                sb.Append("   displayScheduledTrips(map,scheduledTrips);");
            }
            if (showDealerTrips)
            {
                sb.Append("   displayScheduledDealerTrips(map,scheduledDealerTrips);");
            }
            //display ABC Marker

            sb.Append("    }; ");

            #region populate/set array
            if (showTrips == true)
            {
                sb.Append("var  scheduledTrips=[ ");
                foreach (ABC.Google.currentTrips x in currTrips)
                {
                    sb.Append("['" + x.invoice + "', " + x.Latitude + "," + x.Longitude + ",'" + x.imagePath + "','" + x.tripDate + "','" + x.tech + "','" + x.category +"','" + x.jobSize + "'],"  );
                }

                sb.Append("];");
            }
            if (showDealerTrips == true)
            {
                sb.Append("var scheduledDealerTrips=[ ");
                foreach (ABC.Google.DealerPickUpRequest x in currDealerTrips)
                {
                    sb.Append("['" + x.Address + "', " + x.Latitude + "," + x.Longitude + ",'" + x.ContentDescription + "','" + x.Dealername + "','" + x.tech + "','" + x.imagePath + "','" + x.tripDate + "'],");
                }
                sb.Append("];");
            }

            if (showWOOnsitePartsReceived == true)
            {
                sb.Append("var  woOnSitePartsReceived=[ ");
                foreach (ABC.Google.WOONsitePartsReceived x in ListOfOnSitePartsReceived)
                {
                    sb.Append("['" + x.invoice + "'," + x.Latitude + "," + x.Longitude + ",'" + x.ContentDescription + "','" + x.TAT + "'],");
                }
                sb.Append("];");

            }
            if (showUnitRequiringMoreInfo == true)
            {
                sb.Append("var  unitsRequiringMoreInfo =[ ");
                //add data here
                foreach (ABC.Google.UnitsRequiringMoreInfo x in ListOfUnitsNeedingMoreInfo)
                {
                    sb.Append("['" + x.invoice + "'," + x.Latitude + "," + x.Longitude + ",'" + x.ContentDescription + "','" + x.TAT + "'],");
                }

                sb.Append("];");
            }

            if (showPartsIn7OrLessDays == true)
            {
                sb.Append("var  partsIn7OrLessDays =[ ");
                //add data here
                foreach (ABC.Google.PartsIn7orLessDays x in ListOfParts7OrLessDays)
                {
                    sb.Append("['" + x.invoice + "'," + x.Latitude + "," + x.Longitude + ",'" + x.ContentDescription + "','" + x.TAT + "'],");
                }

                sb.Append("];");
            }
            #endregion
            #region display Markers
           
            sb.Append(@" function displayMarkers(map, locations,path)
                             {
                                //var image = new google.maps.MarkerImage(path);
                                var image = new google.maps.MarkerImage(path);

                                for (var i = 0; i < locations.length; i++) {
                                    var beach = locations[i];
                                    var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
                                  
                                    var contentString = beach[3];
            
                                    var marker = new google.maps.Marker({
                                        position: myLatLng,
                                        map: map,
                                        icon: image,
                                        title: 'WO: ' + beach[0] + ' TAT: ' + beach[4], 
                                        animation: google.maps.Animation.DROP    
                                    });

                                        (function(tripInfo,marker) {
                                            google.maps.event.addListener(marker, 'click',function(){
                                              if(!infowindow) {
                                                infowindow = new google.maps.InfoWindow();
                                              }
                                              infowindow.setContent(tripInfo);
                                              infowindow.open(map,marker);
                                            });
                                          })(contentString,marker);
                                    
                                  }// end of loop
                              
                             }// end of setMarkers function
                ");
            #endregion
            #region Scheduled Trips
            //  var contentString = '<table ><tr><td>WO#</td><td>' +beach[0] + 
            //  var contentString = '<p><b><h3>WO: '+ beach[0] +'</h3><h4> ' + beach[4] +'</h4><h4>Tech: ' + beach[5] +' </h4></p><p>Category: ' + beach[6] + '</p> ';
            sb.Append(@"
                              //variable to hold the infowindow object
                              var infowindow;
                              function displayScheduledTrips(map, locations)
                             {
                                                             
                                for (var i = 0; i < locations.length; i++) {                          
                                            var beach = locations[i];
                                            var image = new google.maps.MarkerImage(beach[3]);
                                            var myLatLng = new google.maps.LatLng(beach[1], beach[2]);
            
                              ");

                            sb.Append(" var contentString = '<table border=\"1\" cellpadding=\"1\">");
                            sb.Append("<tr><td><b>Scheduled Trip </b> </td><td><img src=\"' + image + '\"></td></tr>");
                            sb.Append("<tr><td>WO: ' + beach[0] + '</td><td>' + beach[4] + '</td><td>Tech: ' + beach[5] + '</td></tr>");
                            sb.Append("<tr><td>Category: ' + beach[6] + '</td><td>JobSize: ' + beach[7] + '</td></tr>");
                            sb.Append("</table>';");
                    
          
                                sb.Append(@"                            

                                            var marker = new google.maps.Marker({
                                                position: myLatLng,
                                                map: map,
                                                icon: image,
                                                title: 'WO: ' + beach[0]   ,
                                                animation: google.maps.Animation.DROP                                
                                            }); // end of marker
                                   
                                        (function(tripInfo,marker) {
                                        google.maps.event.addListener(marker, 'click',function(){
                                          if(!infowindow) {
                                            infowindow = new google.maps.InfoWindow();
                                          }
                                          infowindow.setContent(tripInfo);
                                          infowindow.open(map,marker);
                                        });
                                       })(contentString,marker);

                               
                                }//end of for loop

                             }// end of setMarkers function
                ");
            #endregion
            #region Scheduled Dealer Trips

            sb.Append(@"
                              //variable to hold the infowindow object
                              var infowindow;
                              function displayScheduledDealerTrips(map, locations)
                             {
                                                             
                                for (var i = 0; i < locations.length; i++) {                          
                                            var beach = locations[i];
                                            var image = new google.maps.MarkerImage(beach[6]);
                                            var myLatLng = new google.maps.LatLng(beach[1], beach[2]);

                                            var contentString = '<p><b><h3>Dealer: '+ beach[4] +'</h3><h4>Tech: ' + beach[5] +' </h4></p><p>ContentDesc: ' + beach[3] + '</p> ';
                                     
                                            var marker = new google.maps.Marker({
                                                position: myLatLng,
                                                map: map,
                                                icon: image,
                                                title: 'Dealer: ' + beach[4]                                   
                                            }); // end of marker
                                   
                                        (function(tripInfo,marker) {
                                        google.maps.event.addListener(marker, 'click',function(){
                                          if(!infowindow) {
                                            infowindow = new google.maps.InfoWindow();
                                          }
                                          infowindow.setContent(tripInfo);
                                          infowindow.open(map,marker);
                                        });
                                       })(contentString,marker);

                                }//end of for loop

                             }// end of setMarkers function
                ");
            #endregion
            sb.Append(" </script>");
            js.Text = sb.ToString();
        }
        protected void BuildTripMap_Click(object sender, EventArgs e)
        {
           // DropDownTechs.SelectedValue = Session["SelectTech"].ToString();
            if (txtStartDate.Text != "" && txtEndDate.Text != "")
            {
                startDate = Convert.ToDateTime(txtStartDate.Text);
                endDate = Convert.ToDateTime(txtEndDate.Text);
                showTrips = true; // this.chkboxTrips.Checked;
                showDealerTrips = this.chkboxDealers.Checked;
                if (showTrips)
                {
                    currTrips = ABC.Trips.Trips.getListOfTrips(startDate, endDate, DropDownTechs.SelectedValue, listOfUnfindableAddresses);
                    List<ABC.Trips.Trips.JobSizeInfo> x = ABC.Trips.Trips.getJobSize(startDate, endDate, DropDownTechs.SelectedValue);

                    JobSizeRepeater.DataSource = from c in x select new { jobSize = c.jobSize, TripDate = c.TripDate };
                    JobSizeRepeater.DataBind();
                }
                if (showDealerTrips)
                    currDealerTrips = ABC.Trips.Trips.getDealerPickUpRequests(startDate, endDate, DropDownTechs.SelectedValue);

                DayPilotCalendar1.StartDate = startDate;
                DayPilotCalendar1.Days = Convert.ToInt16((endDate - startDate).TotalDays) + 1;
                DayPilotCalendar1.DataStartField = "start";
                DayPilotCalendar1.DataEndField = "end";
                DayPilotCalendar1.DataTextField = "name";
                DayPilotCalendar1.DataValueField = "id";
                DayPilotCalendar1.DataSource = ABC.Trips.Trips.getRecords(DayPilotCalendar1.StartDate, DayPilotCalendar1.Days, DropDownTechs.SelectedValue);
                DayPilotCalendar1.DataBind();

                ListBox1.DataSource = listOfUnfindableAddresses;
                ListBox1.DataBind();
            }

            Session["SelectTech"] = DropDownTechs.SelectedValue;

            showWOOnsitePartsReceived = this.chkBoxWOONsitePartsReceived.Checked;
            showUnitRequiringMoreInfo = this.chkboxUnitsRequiringMoreInfo.Checked;
            showPartsIn7OrLessDays = this.chkboxpartsIn7OrLessDays.Checked;

            if (showPartsIn7OrLessDays)
            {

                ListOfParts7OrLessDays = ABC.WorkOrders.WorkOrder.getPartsIn7orLessDays(departmentsDropDown.SelectedValue, categoriesDropDown.SelectedValue);
               // Repeater1.DataSource = from c in ListOfParts7OrLessDays select new { invoice = c.invoice, tat = c.TAT, zip = c.ZipCode, city = c.City };
                //Repeater1.DataBind();

                //show data in repeater control on its own tab
                 this.partsHereIn7orLessDaysRepeater.DataSource = ABC.WorkOrders.WorkOrder.getPartsIn7orLessDays();
                 this.partsHereIn7orLessDaysRepeater.DataBind();

            }

            if (showUnitRequiringMoreInfo)
            {
                List<ABC.Google.UnitsRequiringMoreInfo> xy;
                ListOfUnitsNeedingMoreInfo = ABC.WorkOrders.WorkOrder.getUnitsRequiringMoreInfo(out xy,"");
          
                this.unitsNeedingMoreInfoRepeater.DataSource = ABC.WorkOrders.WorkOrder.getUnitsRequiringMoreInfo();
                this.unitsNeedingMoreInfoRepeater.DataBind();
            }

            if (showWOOnsitePartsReceived)
            {
                List<ABC.Google.WOONsitePartsReceived> xy;
                ListOfOnSitePartsReceived = ABC.WorkOrders.WorkOrder.getWOOnsitePartsReceived();

                this.gridViewReceivedParts.DataSource = ListOfOnSitePartsReceived;
                this.gridViewReceivedParts.DataBind();

                //Repeater3.DataSource = from c in ListOfOnSitePartsReceived select new { invoice = c.invoice, tat = c.TAT, zip = c.Zip, city = c.City };
                //Repeater3.DataBind();
            }
            BuildScript();
        }
        protected void BuildTripDirections_Click(object source, EventArgs e)
        {
            showCurrentTripsInGoogleMaps();
        }
        /// <summary>
        /// Will display the current trips of in google maps. 
        /// </summary>
        private void showCurrentTripsInGoogleMaps()
        {
            StringBuilder strBuilder = new StringBuilder();
            try
            {
                startDate = Convert.ToDateTime(txtStartDate.Text);
                endDate = Convert.ToDateTime(txtEndDate.Text);

                currTrips = ABC.Trips.Trips.getListOfTrips(startDate, endDate, DropDownTechs.SelectedValue, listOfUnfindableAddresses);
                strBuilder.Append("http://maps.google.com/maps?saddr=101 Lincoln Parkway, Rochester, NY 14445&daddr=");
                foreach (ABC.Google.currentTrips trip in currTrips)
                {
                    strBuilder.Append(trip.address);
                    strBuilder.Append(" ");
                    strBuilder.Append(trip.City);
                    strBuilder.Append(", ");
                    strBuilder.Append(trip.state);
                    strBuilder.Append(" ");
                    strBuilder.Append(trip.Zip);
                    strBuilder.Append("+to:");
                }
                strBuilder.Append("101 Lincoln Parkway, Rochester, NY 14445");
                //Create a new process.
                System.Diagnostics.Process proc = new System.Diagnostics.Process();
                proc.EnableRaisingEvents = false;
                proc.StartInfo.FileName = strBuilder.ToString();
                proc.Start();
            }
            catch (Exception ex)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "ExceptionMessage", "alert('" + ex.Message + "');", true);
      
            }
        }
    }
}